import React from 'react';
import { Button, Result } from 'antd';

type ErrorBoundaryProps = {
  children: React.ReactNode | React.ReactNode[];
};

export default class ErrorBoundary extends React.Component<
  ErrorBoundaryProps,
  { error: Error; errorInfo: { componentStack: string } }
> {
  state = {
    error: { name: '', message: '', stack: '' },
    errorInfo: { componentStack: '' },
  };

  static getDerivedStateFromError(err: Error) {
    return { error: err, errorInfo: { componentStack: '' } };
  }
  componentDidCatch(error: Error, errorInfo: { componentStack: string }) {
    this.setState({
      error,
      errorInfo: { componentStack: errorInfo.componentStack },
    });
  }

  clearErr = () => {
    this.setState(
      {
        error: { name: '', message: '' },
        errorInfo: { componentStack: '' },
      },
      () => {
        location.pathname = '/';
        sessionStorage.removeItem('menu');
      }
    );
  };
  render() {
    const { error, errorInfo } = this.state;
    if (error && error.name) {
      return (
        <Result
          status="error"
          title={error.message}
          subTitle="请检查你代码中的错误，或者尝试刷新页面"
          extra={[
            <Button type="primary" key="console" onClick={this.clearErr}>
              返回
            </Button>,
            <Button key="buy" onClick={() => location.reload()}>
              刷新页面
            </Button>,
          ]}
        >
          <div className="desc">
            <pre>
              <code>{error.message}</code>
              <code>{errorInfo && errorInfo?.componentStack}</code>
            </pre>
          </div>
        </Result>
      );
    }
    return this.props.children;
  }
}
